package cc.langk.core.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ajax 分页的属性
 * 
 * @author 朱建文 创建时间：2017年12月7日 下午7:49:00
 */
public class XPaging<T> {

	// WhereMap 接受页面传递的参数
	protected Wm<String, Object> wm = new Wm<String, Object>();

	public static final int DEFAULT_PAGE_SIZE = 10; // 默认数据条数

	/**
	 * 查询对象
	 */
	private Query query;

	// 组装完 sql 后的参数 集合
	protected List<Object> param = new ArrayList<Object>();

	/**
	 * 查询数据的起始条数
	 */
	private int offset;

	/**
	 * 查询数据的条数
	 */
	private int limit;

	/**
	 * 排序 方式
	 */
	private String order;

	/**
	 * 排序 字段
	 */
	private String sort;

	/**
	 * 每页大小
	 */
	private int pageSize;

	/**
	 * 当前页数
	 */
	private int curPage;

	public XPaging() {
		this(0, 1, DEFAULT_PAGE_SIZE);
	}

	public XPaging(int total) {
		this(total, 1, DEFAULT_PAGE_SIZE);
	}

	public XPaging(int total, int page) {
		this(total, page, DEFAULT_PAGE_SIZE);
	}

	public XPaging(int total, int page, int size) {
		curPage = page;
		pageSize = size;
		calculate();
	}

	private void calculate() {
		if (pageSize < 1) {
			pageSize = DEFAULT_PAGE_SIZE;
		}

		if (curPage < 1) {
			curPage = 1;
		}
		
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(Integer offset) {
		this.offset = offset;
	}

	public int getLimit() {
		return limit > 100 ? 100 : limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public boolean isAsc() {
		return "asc".equals(getOrder());
	}

	public Map<String, Object> getWm() {
		return wm;
	}

	public void setWm(Wm<String, Object> wm) {
		this.wm = wm;
	}

	public void setPageSize(int size) {
		pageSize = size;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public void setOffset(int offset) {
		this.offset = offset;
		if (offset > 0) {
			curPage = offset / getPageSize();
			curPage += 1;
		}
	}

	/**
	 * 初始化 查询
	 */
	public Query createQuery() {
		query = query == null ? new Query() : query;
		return query;
	}

	public Query getQuery() {
		query = query == null ? new Query() : query;
		return query;
	}

	public void setQuery(Query query) {
		this.query = query;
	}

	public List<Object> getParam() {
		return param;
	}

	public void setParam(List<Object> param) {
		this.param = param;
	}

	/**
	 * 得到 查询的 sql 语句 不包含 where 之前的语句
	 */
	public String getWhereSQL() {
		param = new ArrayList<Object>();
		String sql = SqlParse.parse(wm, param, createQuery());
		if (sql != null && sql.startsWith(" AND")) {
			sql = " " + sql.substring(4, sql.length());
		}
		return sql;
	}

}
